package com.jp.knowledge.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.DisplayUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.activity.SearchActivity;
import com.jp.knowledge.activity.TeamCircleActivity;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.Banner;
import com.jp.knowledge.model.FoundBanner;
import com.jp.knowledge.model.FoundItem;
import com.jp.knowledge.model.FundAppHome;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.CustomScrollViewPager;
import com.jp.knowledge.view.DotLayout;
import com.jp.knowledge.view.FoundGridItem;
import com.jp.knowledge.view.FoundItemView;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by jiayen on 16/9/28.
 */
public class FoundFragment extends BaseFragment implements View.OnClickListener, ResultSubscriber.OnResultListener {

    private View mView;
    private Context mContext;

    @ViewInject(R.id.main_layout)
    private LinearLayout mainLayout;
    @ViewInject(R.id.module_name)
    private TextView topName;
    @ViewInject(R.id.module_desc)
    private TextView topDesc;
    @ViewInject(R.id.img_pager)
    private CustomScrollViewPager imgPager;
    @ViewInject(R.id.dot_layout)
    private DotLayout dotLayout;
    @ViewInject(R.id.team_circle)
    private FoundItemView itemView;

    private FoundBanner banners;                 //首页轮播图片加  竞圈数据
    private FileCacheManager cacheManager;      //缓存
    private String BANNER_PATH;                 //banner缓存路径
    private String APPDATA_PATH;                //appdata缓存路径

    private BroadcastReceiver broadcastReceiver;
    private LocalBroadcastManager localBroadcastManager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.found_fragment, null);
        this.mContext = getActivity();
        x.view().inject(this, mView);
        init();
        return mView;
    }

    private void init() {
        initHead(mView);
        topName.setText("发现");
        topDesc.setText("为你连接一切");
        rightIcon.setVisibility(View.VISIBLE);
        rightIcon.setOnClickListener(this);
        itemView.setOnClickListener(this);
        setScoop();

        initCacheInfo();
        initBroadCast();

        readBannerCache();
        readAppData();
    }

    private void initBroadCast() {
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if(!LocalBroadCast.CONNECT_NET_BROAD.equals(intent.getAction()))
                    return;
                if(imgPager.getAdapter().getCount() == 0)
                    getBannerData();
                if(mainLayout.getChildCount() == 0)
                    getAppData();
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocalBroadCast.CONNECT_NET_BROAD);
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(broadcastReceiver);
    }

    private void setScoop() {
        FoundItem item = new FoundItem();
        item.setResId(R.mipmap.faxiantuanduiquan);
        item.setShowTip(true);
        item.setName("团队圈");
        itemView.setItem(item);
    }

    /* 初始化缓存信息 */
    private void initCacheInfo() {
        cacheManager = new FileCacheManager();
        BANNER_PATH = mContext.getCacheDir()+"/banner_" + HttpHelper.uuid + ".dat";     //banner缓存路径
        APPDATA_PATH= mContext.getCacheDir()+"/appdata_" + HttpHelper.uuid + ".dat";    //app数据缓存路径
    }

    /* 读取缓存的轮播图片数据 */
    private void readBannerCache(){
        Observable.create(new Observable.OnSubscribe<FoundBanner>() {
            @Override
            public void call(Subscriber<? super FoundBanner> subscriber) {
                FoundBanner appData = (FoundBanner) cacheManager.readObject(BANNER_PATH);
                subscriber.onNext(appData);
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<FoundBanner>() {
            @Override
            public void onCompleted() {
                getBannerData();
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(FoundBanner data) {
                banners = data;
                if(banners != null)
                    setBannerData();
                onCompleted();
            }
        });
    }
    /* 读取缓存的应用数据 */
    private void readAppData(){
        Observable.create(new Observable.OnSubscribe<List<FundAppHome>>() {
            @Override
            public void call(Subscriber<? super List<FundAppHome>> subscriber) {
                List<FundAppHome> appData = (List<FundAppHome>) cacheManager.readObject(APPDATA_PATH);
                subscriber.onNext(appData);
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<List<FundAppHome>>() {
            @Override
            public void onCompleted() {
                getAppData();
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(List<FundAppHome> data) {
                if(data != null)
                    setAppData(data);
                onCompleted();
            }
        });
    }

    /*  设置 banner 数据*/
    private void setBannerData(){
        if (banners != null) {
            List<Banner> list = banners.getBanner();
            if (list != null && list.size() > 0) {
                dotLayout.initView(list.size());
                imgPager.update(list, dotLayout);
            }
        }
    }

    /* 设置应用数据 */
    private void setAppData(List<FundAppHome> list){
        int i = 0;
        int size =list.size();
        mainLayout.removeAllViews();
        for (FundAppHome home : list) {
            FoundGridItem  gridItem = new FoundGridItem(mContext);
            gridItem.setHomeData(home);
            mainLayout.addView(gridItem);
            if(i != size-1){
                mainLayout.addView(getLineView());
                i++;
            }
        }
    }

    private View getLineView(){
        View view = new View(mContext);
        view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, DisplayUtil.dip2px(mContext,10)));
        view.setBackgroundResource(R.color.found_item_line);
        return view;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case  R.id.icon_serach:
                startActivity(new Intent(mContext, SearchActivity.class));
                break;
            case R.id.team_circle:
                startActivity(new Intent(mContext, TeamCircleActivity.class));
                break;
        }
    }

    private final static int GET_BANNER_CODE = 0x01;
    private final static int GET_APPDATA_CODE = 0x02;
    /* 获取轮播图片数据 */
    private void getBannerData(){
        HttpHelper.getInstance(mContext).discoverData(new JsonObject(), GET_BANNER_CODE, this);
    }
    /* 获取体验数据 */
    private void getAppData(){
        HttpHelper.getInstance(mContext).discoverApps(new JsonObject(), GET_APPDATA_CODE, this);
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {}
    @Override
    public void onError(int requestType) {}
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            onError(requestType);
            return;
        }
        if(requestType == GET_BANNER_CODE) {
            banners = data.getEntity(FoundBanner.class);
            if(banners != null) {
                setBannerData();
                saveDataToCache(banners, BANNER_PATH);
            }
        } else if(requestType == GET_APPDATA_CODE){
            List<FundAppHome> list = data.getList(FundAppHome.class);
            if(list != null) {
                setAppData(list);
                saveDataToCache(list, APPDATA_PATH);
            }
        }
    }
    /* 缓存数据到本地 */
    private void saveDataToCache(final Object data, final String path){
        new Thread(new Runnable() {
            @Override
            public void run() {
                cacheManager.wirteObject(data, path);
            }
        }).start();
    }
}
